<?php
/**
 * 
 * 系统用户相关model
 */

class SystemModel extends Cola_Model {
	
    protected $_table = 'guoce_system_users'; //表名
    protected $_pk = 'uid';      //主键
    
	const COOKIE_EXPIRING_DATE = 7200;             //cookie过期时间
    const COOKIE_PATH = '/';
	
    /**
     * 
     * 添加信息
     * @param array $data
     * @return int|bool
     */
    public function add( $data ){
    	$result = false;
    	if( is_array($data) && isset($data['username']) && $data['username'] != '' && isset($data['password']) && $data['password'] != '' ){
    		$checkExist = $this->checkExist( $data['username']);
    		if( $checkExist == false ){
    			$result = $this->insert($data);
    		}
    	}
    	return $result;
    }
    
    /**
     * 
     * 修改信息
     * @param int $id
     * @param array $data
     * @return int|bool
     */
    public function edit( $id, $data ){
    	$result = false;
    	$id = intval($id);
        if( is_array($data) ){
    		$result = $this->update($id, $data);
    	}
    	return $result;
    }
    
    /**
     * 
     * 删除信息
     * @param int $id
     * @return bool
     */
    public function del( $id ){
    	$result = false;
    	is_int($id) && $result = $this->delete($id);
    	return $result;
    }
   
    /**
     * 
     * 根据ID取一条信息
     * @param int $id
     * @return array
     */
    public function getInfoById( $id ){
    	$result = false;
    	is_int($id) && $result = $this->load($id);
    	return $result;    	
    }
    
	/**
	 * 
	 * 验证用户是存在
	 * @param str $usename
	 * @param int $uid （修改用户需传）
	 * @return array
	 */
    public function checkExist( $username, $uid = 0 ){
    	$uid = intval($uid);
    	if( $uid > 0 ){
    		$where = " and `uid` != " . $uid;
    	}else{
    		$where = '';
    	}
    	$sql = "select uid from ". $this->_table . " where `username` = '" . $username . "'" . $where;
    	$result = $this->sql($sql);
    	return $result;
    }
    
	/**
	 * 
	 * 取用户列表或总数
	 * @param bool $count  是否取总数
	 * @param int $page    页码
	 * @param int $limit   每页取多少
	 * @return bool|array  结果
	 */
    public function getList($count = false, $page = 1,  $limit = 20) {
    	$result = false;
    	if( $count ){//取总数
    		$result = $this->count(' 1=1 ');
    	}else{
    		$result = $this->sql('select * from ' . $this->_table . ' order by uid desc limit ' . $limit . ' offset ' . ($page-1)*$limit . ' ;');
    	}
    	return $result;
    }
	
    /**
     * 
     * 系统用户登录
     * @param str $username
     * @param str $password
     * @return int
     */
    public function login($username, $password) {
    	$result = false;
        try {
        	$password = MD5(MD5($password));
            $userInfo = $this->sql("select * from " . $this->_table . " where `username` = '$username' and `password` = '$password' and status = 1 limit 1");
            if( !empty($userInfo) && is_array($userInfo) ){
				$authInfo = array('uid' => $userInfo[0]['uid'], 
								  'username' => $userInfo[0]['username'], 
								  'utype' => $userInfo[0]['user_type'],
				                  'loginIp' => Cola_Request::clientIp(),
				                  'loginTime' => time());
				$authInfo = base64_encode(serialize($authInfo));
				
				$_SESSION['GUOCE'] = $authInfo;
				
				//更新登陆信息
				$this->edit( $userInfo[0]['uid'], array('last_login_time' => time(), 'last_login_ip' => ip2long(Cola_Request::clientIp())) );
				
				$result = true;
            }
        } catch (Exception $e) {
            $result = false;
        }
        return $result;
   }
    
    /**
     * 
     * 登出系统
     */
    public function loginOut(){
//     	Cola_Response::cookie('GUOCE', null, -86400 * 365, self::COOKIE_PATH, Cola::config('_cookieDomain'));
		session_destroy();
    	Cola_Response::redirect('/admin/login/index');
    }
    
    /**
     * 取登录后的用户信息
     * @return array
     */
    public function getLoginInfo(){
		$loginInfo = array();
		
		if(isset($_SESSION['GUOCE'])){
			$loginInfo = $_SESSION['GUOCE'];
			$loginInfo = unserialize(base64_decode($loginInfo));
			
		}
		
		return $loginInfo;
// 		$info = Cola_Request::cookie('GUOCE'); 
// 		if(!empty($info)){
// 			$loginInfo = unserialize(base64_decode($info));
//			if( (time() - $loginInfo['loginTime']) > (self::MEM_EXPIRING_DATE - 100) ){ //如登录即将超时，更新缓存和cookie时间
//				Cola_Response::cookie('WOW', $info, time() + self::COOKIE_EXPIRING_DATE, self::COOKIE_PATH, Cola::config('_cookieDomain'));
//			}
// 		}
// 		return $loginInfo;
    }

}